// pages/brand_list/index.js
import {
    getNavigationbar,
    RePetService
} from "../../api/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        keyword: '',
        nvaigateName: "",
        scrollViewHeight: 0,
        active: 0,
        numGood: 0,Benlen:true,
        tabsList: ['产品', '品牌介绍'],
        goodsList: [],
        isSpecs: false,
        isAhow: false,
        hanEnow:true,
        thumb: null,
        activity: [],
        obj: {},
        params: {},
        currentPage: 1, // 当前页码
        brandIntro: "",isAshow:false,
        cartGoodDetail: {} //购物车商品数据
    },
    onScrollViewScroll: function (e) {
        if (e.detail.scrollTop >= 10) { // 当滚动到200px位置时添加样式
            this.setData({
                isAshow: true,
                scrollViewHeight:700
            });
        } else {
            this.setData({
                isAshow: false
            });
        }
        console.log('eeee')
        // 在这里可以处理scroll-view滚动时的逻辑
    },
    nood() {
        console.log('点击', this.data.subdata)
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        wx.reLaunch({
            url: `/pages/goods_cart/index`,
        })

    },
    getShoppingCartList(item) {
        getNavigationbar({
            act: 'getcartsp',

        }).then(res => {
            console.log('购物车列表-一件代发', res)
            this.setData({
                numGood: res.numbers
            })

        });
    },
    handleScrollToLower() {
        console.log('触发到底部提示打印');
        if(this.data.hanEnow == true) {
            let data = {
                currentPage: this.data.currentPage + 1,
                counts: 10,
            }
            this.setData({
                currentPage: this.data.currentPage + 1,
                loading: true
            });
            this.getHttpGoodsList(this.data.params);
        }

    },
    onChange(e) {
        console.log('e', e)
        this.setData({
            keyword: e.detail,
        });
    },
    onSearch() {
        this.data.goodsList = []
        this.data.currentPage = 1
        this.getHttpGoodsList(this.data.params);
    },
    check(e) {
        console.log('e', e)
    },
    /**
     * 执行请求获取数据回调方法数据
     */
    getHttpGoodsList(params) {
        this.data.hanEnow == false
        getNavigationbar({
            act: 'pro_list', //brand_recPro_list
            lack_inventory: 1,
            keyword: this.data.keyword || '',
            brandid: params.brandid || '', // 品牌id
            // agentid: params.agentid, // 供应商id
            p: this.data.currentPage, // 当前页码
        }).then(res => {
            console.log('res', res)
            if(res.result == 60005) {
                return getApp().Tips({
                    title:'没了~'
                })
            }
            if (res) {
            
                res.forEach(element => {
                    if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                        element.sellprice = '***'
                        element.marketprice = '***'
                    }
                    // element.sellprice =  element.sellprice.toFixed(1)
                    // element.marketprice =  element.marketprice.toFixed(1)
                });
                const result = res.map(obj => {
                    const uniqueIds = [...new Set(obj.activity_list.map(item => item.range))];
                    const filteredActive = uniqueIds.map(range => obj.activity_list.filter(item => item.range === range).pop());
                    return {
                        ...obj,
                        activity_list: filteredActive.reverse()
                    };
                });
                this.data.hanEnow == true
                wx.nextTick(() => {
                    this.setData({
                        goodsList: this.data.goodsList.concat(result)
                    })
                })
            }
        })
    },
    /**
     * 品牌标签选择回调函数方法
     * @param {*} e 
     */
    handleSelTabs(e) {
        const {
            index
        } = e.currentTarget.dataset
        this.setData({
            active: index
        })
        console.log(this.data.params)

        if (index == 0) {
            this.getHttpGoodsList(this.data.params)
        } else {
            this.getRePetService()
        }
    },
    getRePetService() {
        RePetService({
            act: 'getBrandIntroduce',
            brand_id: this.data.params.brandid, // 供应商id
        }).then(res => {
            console.log("res", res)
            const richText = res.introduce;
            const formattedRichText = this.formatRichText(richText, "brand-introduce");
            if(res.length == 0) {
               this.setData({
                isAshow:true
               })
            }
            console.log(formattedRichText);
            res.introduce = formattedRichText
            console.log('数据',res,res.image)
            if (res) {
                wx.nextTick(() => {
                    this.setData({
                        brandIntro: res
                    })
                })
            }
        })
    },
    formatRichText(html, p_class = "fsmp") {
        if (!html) {
            return ''
        }

        let newContent = html
        if (html.indexOf("<img") != -1) {
            newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
                match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "")
                match = match.replace(/style=""/gi, "")
                match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "")
                match = match.replace(/height="[^"]+"/gi, "").replace(/height='[^']+'/gi, "")
                return match
            })
            newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
                match = match.replace(/width:[^;]+;/gi, "max-width:100%;").replace(/width:[^;]+;/gi, "max-width:100%;")
                return match
            })
            newContent = newContent.replace(/<br[^>]*\/>/gi, "")
            newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;padding-bottom: 20px;"')
        }

        newContent = newContent.replace(/<br[^>]*\/>/gi, "")
        newContent = newContent.replace(/<a>/gi, `<a class="${p_class} p_class_color "`)
        newContent = newContent.replace(/<li>/gi, `<li class="${p_class} p_class_color "`)
        newContent = newContent.replace(/\<p/gi, `<p class="${p_class} p_class_color "`)
        newContent = newContent.replace(/\<span/gi, `<span class="${p_class} p_class_color "`)

        return newContent
    },
    /**
     * 首页跳转商品详情页回调函数方法
     */
    handleGoodsDetail(e) {
        const {
            value
        } = e.currentTarget.dataset
        const params = {
            goodsId: "",
            area: "",
            detailType: 1,
            act: "good_detail"
        }
        if (value) {
            const {
                goodsid,
                id
            } = e.currentTarget.dataset.value
            if (goodsid) {
                params.goodsId = goodsid
            } else {
                params.goodsId = id
            }
        } else {
            const {
                id
            } = e.detail
            params.goodsId = id
        }
        wx.navigateTo({
            url: `/pages/goods_detail/index?data=${JSON.stringify(params)}`,
        })
    },
    /**
     * 选择商品规格加入购物车回调函数方法
     */
    handleJoinCart(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log("value", value)
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        getNavigationbar({
            act: 'good_detail',
            id: value.id
        }).then(res => {
            this.setData({
                isSpecs: true,
                cartGoodDetail: res
            })
        })

        console.log(this.data.cartGoodDetail)
    },
    /**
     * 完成规格选择将商品添加至购物车
     */
    handleConfirm(e) {
        let data = e.detail

        console.log("data", data)
        // if (data.type == 1) {
        getNavigationbar({
            act: 'cart',
            id: data.commodityId || '',
            propertyid: data.data.propertyid || '',
            numbers: data.count || '',
        }).then(res => {
            console.log('添加购物车', res)
            if (res.result == 101) {
                wx.nextTick(() => {
                    getApp().Tips({
                        title: res.msg
                    })
                })
            } else {
                this.setData({
                    isSpecs: false,
                    cartGoodDetail: {}
                })
                wx.nextTick(() => {
                    getApp().Tips({
                        title: "商品已添加至购物车"
                    })
                })

            }
            this.getShoppingCartList()
        });
        // }


    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.content').boundingClientRect()
        query.exec(res => {
            // 同步获取系统信息
            const systemInfo = wx.getSystemInfoSync();
            // 计算底部安全距离
            const safeBottom = systemInfo.screenHeight - systemInfo.safeArea.bottom;
            let contentHeight = res[0].height;
            that.setData({
                scrollViewHeight: contentHeight - safeBottom
            })
        })
    },
    onShareAppMessage: function () {

        return {
            title: this.data.nvaigateName,
            path: `/pages/brand_list/index?data=${JSON.stringify( this.data.params)}`, // 分享的页面路径
            imageUrl: 'https://static.chonglaoban.cn' + this.data.thumb, // 分享的图片链接
        }
    },
    onShareTimeline: function () {
        return {
            title: this.data.nvaigateName,
            path: `/pages/brand_list/index?data=${JSON.stringify( this.data.params)}`, // 分享的页面路径
            imageUrl: 'https://static.chonglaoban.cn' + this.data.thumb, // 分享的图片链接
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            this.data.params = {
                ...params
            }
            console.log('进', params, this.data.params)
            this.data.activity.push({
                type: params.type,
                buy: params.buy,
                derate: params.derate,
            })
            this.setData({
                nvaigateName: params.name,
                thumb: params.thumb,
                activity: this.data.activity
            })
            wx.nextTick(() => {
                this.getHttpGoodsList(params)
                this.getRePetService()
                this.getShoppingCartList()
            })
        }
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        let res = wx.getStorageSync('USER')
        console.log('setStorageSync', res)
        this.data.obj = res
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.computeScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },


})